package com.sdp.wx.controller;


import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.wx.db.wx_contract.service.IWxContractService;
import com.sdp.wx.db.wx_contract_payment.entity.WxContractPayment;
import com.sdp.wx.db.wx_contract_payment.service.IWxContractPaymentService;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-03-19
 */
@RestController
@RequestMapping("/WxContractPaymentController")
public class WxContractPaymentController {
	
	@Autowired
	private Query query;
	
	@Autowired
	private IWxContractPaymentService iWxContractPaymentService;
	
	@Autowired
	private IWxContractService iWxContractService;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iWxContractPaymentService, WxContractPayment.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody WxContractPayment contractPayment) {
		if(contractPayment==null) {
			return Result.error("合同付款信息为空");
		}
		if(StringUtils.isEmpty(contractPayment.getKeyId())) {
			iWxContractPaymentService.save(contractPayment);
		}else {
			iWxContractPaymentService.updateById(contractPayment);
		}
		
		BigDecimal payAmount = BigDecimal.ZERO;
		BigDecimal payRatio = BigDecimal.ZERO;
		List<WxContractPayment> list = iWxContractPaymentService.queryWxContractPaymentByContractCode(contractPayment.getContractCode());
		for(WxContractPayment p : list ) {
			payAmount = payAmount.add(p.getPayAmount());
			payRatio = payRatio.add(p.getPayRatio());
		}
		iWxContractService.setPayAmountAndRatio(contractPayment.getContractCode(), payAmount, payRatio);
		
		return Result.ok();
	}

}

